package com.shf.lease.web.admin.service.impl;

import com.shf.lease.config.minio.MinioConfig;
import com.shf.lease.config.minio.MinioProperties;
import com.shf.lease.result.Result;
import com.shf.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.BindException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author 叶枫
 * @date 2024/7/5.
 */

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioProperties properties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean bucketExists = minioClient.bucketExists(
                BucketExistsArgs.builder()
                        .bucket(properties.getBucketName())
                        .build());

        if (!bucketExists){
            minioClient.makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(properties.getBucketName())
                            .build());
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(properties.getBucketName())
                            .config(createBucketPolicyConfig(properties.getBucketName()))
                            .build());
    }
        if (file == null){

            throw new BindException("文件名不能为空");
        }else {
            //获取文件名字
            String fileName = file.getOriginalFilename();
            //生成新文件名
            String newFileName  = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"
                    + UUID.randomUUID().toString() + "-" + fileName;
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(properties.getBucketName())
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .object(newFileName)
                            .contentType(file.getContentType())
                            .build());
            return String.join("/",properties.getEndpoint(),properties.getBucketName(),newFileName);

    }
}


    private String createBucketPolicyConfig(String bucketName) {
        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}
